package com.zm.spring.jdbc;

import com.google.gson.Gson;
import com.zm.spring.jdbc.Bean.Account;
import com.zm.spring.jdbc.dao.AccountDao;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/queryAccount")
public class QueryAccountServlet extends BasicServlet {
    protected void queryAccount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //web应用上下文对象 => ApplicationContext
        ServletContext servletContext = this.getServletContext();
        ApplicationContext cxt = (ApplicationContext) servletContext.getAttribute("cxt");

        AccountDao dao = cxt.getBean(AccountDao.class);

        List<Account> accounts = dao.selectAll();

        Gson gson = new Gson();
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(gson.toJson(accounts));

    }
}
